<?php

/*
* 公共接口
*/
class CaseinfoController extends Controller_Base

{

    //获取案件附件信息（查看详情）
    public function caseInfoAction()
    {
        $request = $this->getRequest();
        $id = $request->getQuery('caseId', 0);
        if(empty($id)){
            $this->displayError('缺少必要参数');
        }
        $litigant = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['*'],['where'=>["caseId = {$id} group by cardId"]]);
        if(empty($litigant)){
            $this->displayError('未查询到案件信息');
        }
        if(count($litigant)>1){
            foreach ($litigant as $key => $val){
                $showFields["当事人".($key+1)] = $val['litigantName'];
                $showFields["当事人身份证号".($key+1)] = substr($val['cardId'] , 0 , 6) .'******'. substr($val['cardId'] , -4);
            }
        }else{
            $showFields['当事人'] = $litigant[0]['litigantName'];
            $showFields['当事人身份证号'] = substr($litigant[0]['cardId'] , 0 , 6) .'******'. substr($litigant[0]['cardId']);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($id,false);
        $attach = Module_Mediate_CaseAttach::getInstance()->getItemById($id,true,'caseId');
        $fields = Lib_Var::$excel_title['caseDetail'];
        foreach ($fields as $key => $field){
            if(!in_array($key,['litigantName','cardId','telephone'])){
                if($field['check'] == 'checkDate'){
                    $showFields[preg_replace('/\(.*?\)|\（.*?\）/', '', $field['name'])] = !empty($case[$key])?date("Y/m/d H:i:s",$case[$key]):'';
                }else{
                    $showFields[preg_replace('/\(.*?\)|\（.*?\）/', '', $field['name'])] = $case[$key];
                }
            }
        }
        if(!empty($attach)){
            $attachInfo = json_decode($attach['attachInfo'],true);
            if($attachInfo){
                foreach ($attachInfo as $val){
                    if(empty($val['val'])){
                        continue;
                    }
                    $showFields[$val['key']] = $val['val'];
                }
            }

        }
        $showFields['调解员'] = $case['mediatorName'] ? $case['mediatorName'] : $showFields['调解员'];
        SmartyAdapter::assign('showFields',$showFields);


    }
    //更新调解信息
    public function updateMediateLogAction(){
        $request = $this->getRequest();
        $log_id = $request->getPost('log_id', 0);
        $desc = $request->getPost('desc', 0);
        $valid_call = $request->getPost('valid_call', 0);
        $case_id = $request->getPost('case_id', 0);
        if(!$log_id || !$desc || !$valid_call){
            AjaxTool::returnJsonData(4005);
        }
        Func_Log::write("updateMediateLog", $this->admin['id'], $this->admin['name'].'修改'.json_encode($_POST));
        $res = Module_Mediate_CaseMediateLog::getInstance()->update(['valid_call'=>$valid_call,'desc'=>$desc],$case_id,$log_id);
        if($res){
            AjaxTool::returnJsonData(200);
        }
        AjaxTool::returnJsonData(400,'修改失败');

    }
    //获取调解历史
    public function getMediationLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 1);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = array_column($cases,'id');
        $mediateLogs =[];
        $keysValue = [];
        foreach ($case_ids as $caseId){
            $mediateLog = Module_Mediate_CaseMediateLog::getInstance()->getMediateLogByCaseId($caseId);
            if($mediateLog){
                foreach ($mediateLog as $key => &$log){
                    $log['caesId'] =  $caseId;
                    $log['addTime'] =  date("Y/m/d H:i:s",$log['addTime']);
                    $log['type'] =  $log['type'] == 1 ? "呼出" : '呼入';
                    $log['mediateResult'] =  Module_Mediate_Case::$mediateResult[$log['mediateResult']];
                    $log['mobile'] =  $log['mobile'] ? substr_replace($log['mobile'], '****', 3, 4) : '';
                    $log['nextTime'] =  $log['nextTime'] ? date("Y/m/d",$log['nextTime']) : 0;
                    $log['fileName'] =  $log['fileName'] ? SmartyAdapter::getTplVars('soundfileurl').$log['fileName'] : '';
                    $log['mediateType'] =  Module_Mediate_CaseMediateLog::$mediateType[$log['mediateType']];

                    $mediateLogs[] = $log;
                    $keysValue[] = $log['addTime'];

                }
            }
        }
        array_multisort($keysValue, SORT_DESC, $mediateLogs);
        AjaxTool::returnJsonData(200,'操作成功',$mediateLogs);

    }
    //获取短信历史
    public function getSMSLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 1);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $smsLog = Module_Mediate_SmsRecord::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)"],'order'=>"id DESC"]);
        if($smsLog){
            foreach ($smsLog as $key => $log){
                $smsLog[$key]['caseId'] =  $log['caseId'];
                $smsLog[$key]['sendTime'] =  date("Y/m/d H:i:s",$log['sendTime']);
                $smsLog[$key]['sendStatus'] = $log['sendStatus'] == 1 ? "成功" : ( $log['sendStatus'] == 2 ? "发送中":'失败');
                $smsLog[$key]['mobile'] = substr_replace($log['mobile'], '****', 3, 4);
                $smsLog[$key]['scene'] = Lib_SMS_Config::$smsCode[$log['scene']];
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$smsLog);

    }
    //获取操作日志
    public function getOperateLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $operateLog = Module_Mediate_CaseOperationLog::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)"],'order'=>"id DESC"]);
        if($operateLog){
            foreach ($operateLog as $key => $log){
                $operateLog[$key]['createTime'] =  date("Y/m/d H:i:s",$log['createTime']);
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$operateLog);
    }
    //获取还款计划
    public function getReturnedPlanAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 1);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $plan = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)"]]);
        $plans = [];
        if($plan){
            foreach ($plan as $key => &$log){
                $term[$log['caseId']] = $key+1;
                $plan[$key]['term'] =  "第 {$term[$log['caseId']]} 期";
                $plan[$key]['repaymentDate'] =  $log['realRepaymentDate'] ? date("Y/m/d",$log['realRepaymentDate']) :  date("Y/m/d",$log['repaymentDate']);
                $plan[$key]['repayAmount'] =  $log['realRepayAmount'] * 1 ? $log['realRepayAmount'] : $log['repayAmount'];
                $plan[$key]['status'] = Module_Mediate_Case::$planStatusArr[$log['status']];
                $plans[$log['caseId']][] = $plan[$key];
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$plans);
    }
}
